<?php
$cfg = array();
$cfg['chat_broadcast']['host'] = 'localhost';
$cfg['chat_broadcast']['key'] = 'serverkey';
$cfg['chat_broadcast']['port'] = 8000;


$thread = 0;

echo "\n";

for($t = 0; $t < $thread; $t++)
{
	if (pcntl_fork() == 0)
	{
		$start = microtime(true);
		
for($i=100; $i < 150; $i++)
	chat_send("just a test" . $i);
		echo "thread:$t time:" . (microtime(true) - $start) . "\n";
		exit;
	}

}

if ($thread == 0){
for($i=0; $i < 500; $i++)
	chat_send("just a test" . $i);
}



/**
 * 发送广播信息
 * @param String $message
 * @param Integer $message_type 消息类型 100为全服公告 102 为世界boss 103.BOSS战开始前30分钟,104:发送血量通知,105:发送boss奖励全服公告
 */
function chat_send($message, $message_type=100)
{
	global $cfg;
	
	$uid = uniqid("php");
	$nickname = $uid;
	
	$fp = @fsockopen($cfg['chat_broadcast']['host'], $cfg['chat_broadcast']['port'], $errno, $errstr, 1);
	if ($fp){
		$login_pack = pack("s",100) . chat_str($cfg['chat_broadcast']['key']) .chat_str($uid) . chat_str($nickname);
		
		if (@fwrite($fp, pack("i", strlen($login_pack)) . $login_pack) === false){
			return;
		}
		
		$msg_pack = pack("s", 110) . pack("i", $message_type) . chat_str("chat_world") . chat_str($message);
		
		if (fwrite($fp, pack("i", strlen($msg_pack)) . $msg_pack) === false){
			return;
		}

		$ret = fread($fp, 6);
		
		@fclose($fp);
	}
}

/**
 * 发送实时通知
 * 可以同时发送多个
 * 
 * @param Array $arr_messages = index => array("uid" => uid, "type" => "") type:friend box thieve pay boss bossdie bossaward
 */
function chat_notify($arr_messages)
{
	global $cfg;

	$uid = uniqid("phpn");
	$nickname = $uid;

	$fp = @fsockopen($cfg['chat_broadcast']['host'], $cfg['chat_broadcast']['port'], $errno, $errstr, 1);
	if ($fp){
		$login_pack = pack("s",100) . chat_str($cfg['chat_broadcast']['key']) .chat_str($uid) . chat_str($nickname);

		if (@fwrite($fp, pack("i", strlen($login_pack)) . $login_pack) === false){
			return;
		}

		$message_type = 100;
		foreach($arr_messages as $v){
			if (!isset($v['uid']) || !isset($v['type']))
				throwException("chat_notify send error", 111);
			
			$touid = $v['uid'];
			$tomsg = $v['type'];
			$msg_pack = pack("s", 111) . pack("i", $message_type) . chat_str($touid) . chat_str($tomsg);
	
			if (@fwrite($fp, pack("i", strlen($msg_pack)) . $msg_pack) === false){
				return;
			}
			
		}

		$ret = fread($fp, 6);
		@fclose($fp);
	}
}

/**
 * 打包字符串
 * @param String $str
 */
function chat_str($str)
{
		return pack("i",strlen($str)) .   $str;
}
